package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.heima.apis.user.IUserClient;
import com.heima.comment.pojos.*;
import com.heima.comment.service.ApArticleCommentRepayService;
import com.heima.comment.service.CommentAutoScanService;
import com.heima.model.comment.dtos.CommentRepayDto;
import com.heima.model.comment.dtos.CommentRepayLikeDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.vos.PageCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.common.ApUserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @projectName: heima-leadnews-project_training
 * @author: Tyoui
 * @description: 文章回复评论管理业务实现层
 * @date: 2023/8/2 19:17
 */
@Service
public class ApArticleCommentRepayServiceImpl implements ApArticleCommentRepayService {

    @Autowired
    private CommentAutoScanService commentAutoScanService;
    @Autowired
    private MongoTemplate mongoTemplate;
     @Autowired
    private IUserClient userClient;
    /**
     * @param dto:
     * @return ResponseResult
     * @description 保存回复评论
     */
    @Override
    public ResponseResult save(CommentRepaySaveDto dto) {
        // 检查参数
        if (dto == null || StringUtils.isBlank(dto.getCommentId()) || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论字数超过限制");
        }
        ApUser apUser = ApUserThreadLocalUtil.getUser();
        // 判断用户是否登录
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 文本垃圾检测
        boolean result = commentAutoScanService.autoScan(dto.getCommentId());
        if (!result) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论含有敏感信息,无法发布");
        }
        // 构建回复评论对象
        ApUser user = userClient.findUserById(apUser.getId());
        ApArticleCommentReply apArticleCommentReply = ApArticleCommentReply.builder()
                .authorId(apUser.getId())
                .commentId(dto.getCommentId())
                .createdTime(new Date())
                .content(dto.getContent())
                .authorName(user.getName())
                .likes(0)
                .updatedTime(new Date())
                .build();
        mongoTemplate.save(apArticleCommentReply);

        //更新回复数量
        ApArticleComment apArticleComment = mongoTemplate.findById(dto.getCommentId(), ApArticleComment.class);
        apArticleComment.setReply(apArticleComment.getReply()+1);
        mongoTemplate.save(apArticleComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * @param dto:
     * @return ResponseResult
     * @description 加载回复评论列表
     */
    @Override
    public ResponseResult load(CommentRepayDto dto) {
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 默认查询10条
        int size = 10;
        // 设置加载参数
        List<ApArticleCommentReply> replyList = mongoTemplate.find(Query.query(Criteria
                .where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(size), ApArticleCommentReply.class);
        ApUser apUser = ApUserThreadLocalUtil.getUser();
        // 查询哪些评论被点赞了
        List<String> idList = replyList.stream().map(ApArticleCommentReply::getId).collect(Collectors.toList());
        List<ApArticleCommentReplyLIke> replyLikes = mongoTemplate.find(Query.query(Criteria
                .where("commentRepayId").in(idList)
                .and("authorId").is(apUser.getId())), ApArticleCommentReplyLIke.class);
        // 没有被点赞，则返回原数据
        if (replyLikes == null || replyLikes.isEmpty()) {
            return ResponseResult.okResult(replyList);
        }
        List<PageCommentVo> list = new ArrayList<>();
        // 设置operation值,封装结果返回
        replyList.forEach(replyLike->{
            PageCommentVo vo = new PageCommentVo();
            BeanUtils.copyProperties(replyLike, vo);
            for (ApArticleCommentReplyLIke apCommentRepayLike : replyLikes) {
                if(replyLike.getId().equals(apCommentRepayLike.getCommentRepayId())){
                    vo.setOperation(("0"));
                    break;
                }
            }
           list.add(vo);
        });
        return ResponseResult.okResult(list);
    }

    //点赞
    @Override
    public ResponseResult like(CommentRepayLikeDto dto) {
        Query query = Query.query(Criteria.where("_id").is(dto.getCommentRepayId()));
        ApArticleCommentReply apArticleCommentReply = mongoTemplate.findOne(query, ApArticleCommentReply.class);

        //点赞
        if (dto.getOperation() == 0) {
            apArticleCommentReply.setLikes(apArticleCommentReply.getLikes() + 1);
            mongoTemplate.save(apArticleCommentReply);

            ApArticleCommentReplyLIke apArticleCommentReplyLIke = new ApArticleCommentReplyLIke();
            apArticleCommentReplyLIke.setAuthorId(apArticleCommentReply.getAuthorId());
            apArticleCommentReplyLIke.setCommentRepayId(dto.getCommentRepayId());
            mongoTemplate.save(apArticleCommentReplyLIke);
        } else if(dto.getOperation() == 1){
            //取消点赞
            apArticleCommentReply.setLikes(apArticleCommentReply.getLikes() - 1);
            mongoTemplate.save(apArticleCommentReply);
            Query query1 = Query.query(Criteria.where("_id").is(apArticleCommentReply.getAuthorId()));
            ApArticleCommentLike apArticleCommentLike = mongoTemplate.findOne(query1, ApArticleCommentLike.class);
            if (apArticleCommentLike != null) {
                mongoTemplate.remove(apArticleCommentLike);
            }
        }

        Map<String, Integer> map = new HashMap<>();
        map.put("likes",apArticleCommentReply.getLikes());
        return ResponseResult.okResult(map);
    }
}